package com.demo.base.rabbitmq.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description RabbitMQ配置类
 * @date 2023/3/17 4:36 PM
 */
@Configuration
@Data
@Slf4j
@ConfigurationProperties(prefix = "spring.rabbitmq")
public class MqConfig {

    private String host;
    private int port;
    private String userName;
    private String password;
    private String virtualHost;

    /**
     * 连接RabbitMQ，并加载到Bean
     *
     * @return
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory cachingConnectionFactory =
                new CachingConnectionFactory(host, port);
        cachingConnectionFactory.setUsername(userName);
        cachingConnectionFactory.setPassword(password);
        cachingConnectionFactory.setVirtualHost(virtualHost);

        return cachingConnectionFactory;
    }

    /** 定义消息转换器 */
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /** 定义消息模板用于发布消息，并且设置其消息转换器 */
    @Bean
    public RabbitTemplate rabbitTemplate() {

        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
        rabbitTemplate.setMessageConverter(jsonMessageConverter());

        return rabbitTemplate;
    }
}
